package com.eascs.admin.o2o.backfee.controller;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.backfee.entity.O2OComBackFee;
import com.eascs.admin.o2o.backfee.entity.OaBackFeeEntity;
import com.eascs.admin.o2o.backfee.form.ComBackFeeForm;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.backfee.trans.O2oComBackFeeTransFormart;
import com.eascs.admin.o2o.backfee.trans.OaBackFeeTransO2Oloanapply;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.utils.BankNoCheckUtil;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.CustomerView;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.form.ComBackFeeWorkForm;

/**
 * 所有动态表单提交类
 * 
 * @author ycz
 *
 */
@RestController
@RequestMapping("/combackfeesubmit")
public class O2oComBackFeeSubmitController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(O2oComBackFeeSubmitController.class);
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2OComBankFeeService o2OComBankFeeService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	BaseUserUtil userUtils;
	
	@Reference
	ICustomerInfoService iCustomerInfoService;
	/**
	 * 保存退费数据。
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/saveComBackFee_form")
	public BaseRestResult<String> approval(ComBackFeeForm comBackFeeForm) {
		// 判断
		
		/**
		 * 判断是否有划拨，如果有划拨则这笔就只能退没有划拨的费用
		 */
		
		O2oLoanapplyEntity entity = o2oLoanapplyService.findById(comBackFeeForm.getLoanapplyNo());
		
		String ishasHB_Deposit  = o2OComBankFeeService.checkIsHasHB_Deposit(entity.getBillCode()); //判断是否有保证金划拨
		if(!ishasHB_Deposit.equals("0")&&comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO)!=0){
			return BaseRestResult.warn("该单已经存在保证金划拨，如需退保证金，请等待划拨流程走完，如需退其它金额，请将保证金填写为零");
		}
		
		
		if (StringUtil.isEmpty(comBackFeeForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		 boolean hasBackFee =o2OComBankFeeService.isHasBackFee(comBackFeeForm.getLoanapplyNo());
		 if(!hasBackFee){ return BaseRestResult.warn("该单没有需要退的费用"); }
		// boolean hasBackFeeFlow =o2OComBankFeeService.isHasBackFeeFlow(comBackFeeForm.getBackType(),comBackFeeForm.getLoanapplyNo()); 
		 boolean hasBackFeeFlow =o2OComBankFeeService.isHasBackFeeFlow(null,comBackFeeForm.getLoanapplyNo()); 
		 if(!hasBackFeeFlow){ return
				 BaseRestResult.warn("该单退费已有流程在运行中"); //所选类型的
		 }
		//判断金额，扩展表
		LoanapplyExpand loanapplyExpand= loanapplyExpandService.queryLoanapplyNo(comBackFeeForm.getLoanapplyNo());
		loanapplyExpand =o2OComBankFeeService.sumn(loanapplyExpand);
		String payType = "";
		if(comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_DEP+",";
		}
		if(comBackFeeForm.getBackManger().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_MAN+",";
		}
		
		if(comBackFeeForm.getBackRisk().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_RISK+",";
		}
		if(payType.length()>0){
		payType=payType.substring(0,payType.length()-1);//去除最后一个字符
		}
		comBackFeeForm.setPayType(payType);
		
		if(loanapplyExpand.getRetnDeposite()!=null){
			if (comBackFeeForm.getBackDeposite().compareTo(loanapplyExpand.getRetnDeposite()) == 1) {
				return BaseRestResult.warn("应退保证金不能大于未退保证金");
			}
		}else{
			if(comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在保证金退费需求");
			}
		}
		if(loanapplyExpand.getRetnManage()!=null){
			if (comBackFeeForm.getBackManger().compareTo(loanapplyExpand.getRetnManage()) == 1) {
				return BaseRestResult.warn("应退管理费不能大于未退管理费");
			}
		}else{
			if(comBackFeeForm.getBackManger().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在管理费退费需求");
			}
		}
		
		if(loanapplyExpand.getRetnRisk()!=null){
			if (comBackFeeForm.getBackRisk().compareTo(loanapplyExpand.getRetnRisk()) == 1) {
				return BaseRestResult.warn("应退风险补偿金不能大于未退风险补偿金");
			}
		}else{
			if(comBackFeeForm.getBackRisk().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在管理费退费需求");
			}
		}
		
		// 校验银行卡
		String isBankno = BankNoCheckUtil.checkBankNo(comBackFeeForm.getBankAccount());
		if (isBankno.equals(BankNoCheckUtil.IS1619)) {
			return BaseRestResult.warn("银行卡号须16到19之间");
		} else if (isBankno.equals(BankNoCheckUtil.ISNUMBER)) {
			return BaseRestResult.warn("银行卡号必须全为数字");
		} else if (isBankno.equals(BankNoCheckUtil.ISNOT)) {
			return BaseRestResult.warn("银行卡号不符合规范");
		}
	 
		 O2OComBackFee ComBackFeedb= o2OComBankFeeService.queryEntity(comBackFeeForm.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
		// isHasBackFee
		/*
		 * boolean hasBackFee =
		 * o2OComBankFeeService.isHasBackFee(comBackFeeForm.getLoanapplyNo());
		 * if(!hasBackFee){ return BaseRestResult.warn("该单没有需要退的费用"); }
		 * //是否还存在没有退费的 boolean hasrRetn =
		 * o2OComBankFeeService.isHasrRetn(comBackFeeForm.getBackType(),
		 * comBackFeeForm.getLoanapplyNo()); if(!hasrRetn){ return
		 * BaseRestResult.warn("该单不存在所选类型的退费需求"); } //是否已经有 退费类型流程在RUN过程中
		 * boolean hasBackFeeFlow =
		 * o2OComBankFeeService.isHasBackFeeFlow(comBackFeeForm.getBackType(),
		 * comBackFeeForm.getLoanapplyNo()); if(!hasBackFeeFlow){ return
		 * BaseRestResult.warn("该单所选类型的退费已有流程在运行中"); }
		 */
		// 新增一条数据
		 if(ComBackFeedb==null){
				O2OComBackFee o2OComBackFee = new O2OComBackFee();
				O2oComBackFeeTransFormart.fromToFee(o2OComBackFee, comBackFeeForm);
				O2oLoanapplyEntity apply = o2oLoanapplyService.findById(comBackFeeForm.getLoanapplyNo());
				o2OComBackFee.setBillCode(apply.getBillCode());
				QueryCustomerVO vo = new QueryCustomerVO();
				vo.setCustomer_id(apply.getLoanId());
				CustomerView customer = iCustomerInfoService.geCustomerView(vo);
				o2OComBackFee.setAccountName(customer.getBasicInfo().getCustomerName());
				o2OComBackFee.setDataSource(StatusContexts.DATA_SOURCE_NEW);
				o2OComBackFee.setLoanerName(customer.getBasicInfo().getCustomerName());
				o2OComBackFee.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
				o2OComBackFee.setCreatorId(userUtils.getCreateOr());
				o2OComBackFee.setCreatTime(userUtils.getCreateTime());
				o2OComBackFee.setCreatorName(userUtils.getUserName());
				o2OComBankFeeService.save(o2OComBackFee);
				o2OComBankFeeService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_NEW, apply.getLoanapplyNo());
		 }else{
			 O2oComBackFeeTransFormart.fromToFee(ComBackFeedb, comBackFeeForm);
			 o2OComBankFeeService.updateById(ComBackFeedb);
		 }
		 if(ComBackFeeForm.TYPE_SAVEANDSTART.equals(comBackFeeForm.getType())){ //如果是保存并启动，调用启动方法
			 //先查出要启动的对象
			 O2OComBackFee startO2OComBackFee =  o2OComBankFeeService.queryEntity(comBackFeeForm.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
			 oaStartUp(startO2OComBackFee.getId());
			/* if(result.getData()!=null){
				 
			 }else{
				 return BaseRestResult.info("数据保存成功，流程启动失败请手动启动").andRedirect(UrlHelper.build("/backfee/list"));
			 }*/
		 }
		 return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/backfee/list"));
	}
	
	/**保存退费记录
	 * 老系统
	 * @param comBackFeeForm
	 * @return
	 */
	@RequestMapping(value = "/saveComBackFee_form_oa")
	public BaseRestResult<String> approval_oa(ComBackFeeForm comBackFeeForm) {
		// 判断
		if (StringUtil.isEmpty(comBackFeeForm.getLoanapplyNo())) {
			return BaseRestResult.warn("贷款单号不能为空");
		}
		
		OaBackFeeEntity oaBackFee = o2OComBankFeeService.findOaBackFeeById(comBackFeeForm.getLoanapplyNo());
		String ishasHB_Deposit  = o2OComBankFeeService.checkIsHasHB_Deposit(oaBackFee.getBillCode()); //判断是否有保证金划拨
		if(!ishasHB_Deposit.equals("0")&&comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO)!=0){
			return BaseRestResult.warn("该单已经存在保证金划拨，如需退保证金，请等待划拨流程走完，如需退其它金额，请将保证金填写为零");
		}
		
		 //判断老系统是否还有没有退完的费用
		 boolean hasBackFee =o2OComBankFeeService.isHasBackFeeOa(comBackFeeForm.getLoanapplyNo());
		 if(!hasBackFee){ return BaseRestResult.warn("该单没有需要退的费用"); }
		 
		 //判断是否有单在新系统中退费，如果有则不让新增
		 boolean hasBackFeeFlow =o2OComBankFeeService.isHasBackFeeFlow(null,comBackFeeForm.getLoanapplyNo());  
		 if(!hasBackFeeFlow){ return
				 BaseRestResult.warn("该单在新系统中已经存在退费流程在运行中"); //所选类型的
		 }
		 //判断老系统中是否有流程正在退费（包括保证金和管理费）
		 boolean hasBackFeeFlowInOa =o2OComBankFeeService.isHasBackFeeFlowInOa(comBackFeeForm.getLoanapplyNo());  
		 if(!hasBackFeeFlowInOa){ return
				 BaseRestResult.warn("该单在老系统中已经存在退费流程在运行中"); //所选类型的
		 }
		 //老系统中的应收，实收，已退，未退
		OaBackFeeEntity oaBackFeeEntity = o2OComBankFeeService.findOaBackFeeById(comBackFeeForm.getLoanapplyNo());
		LoanapplyExpand loanapplyExpand = OaBackFeeTransO2Oloanapply.transloanapplyExpand(oaBackFeeEntity);
		loanapplyExpand =o2OComBankFeeService.sumn(loanapplyExpand);
		
		if(loanapplyExpand.getRetnDeposite()!=null){
			if (comBackFeeForm.getBackDeposite().compareTo(loanapplyExpand.getRetnDeposite()) == 1) {
				return BaseRestResult.warn("应退保证金不能大于未退保证金");
			}
		}else{
			if(comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在保证金退费需求");
			}
		}
		if(loanapplyExpand.getRetnManage()!=null){
			if (comBackFeeForm.getBackManger().compareTo(loanapplyExpand.getRetnManage()) == 1) {
				return BaseRestResult.warn("应退管理费不能大于未退管理费");
			}
		}else{
			if(comBackFeeForm.getBackManger().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在管理费退费需求");
			}
		}
		
		if(loanapplyExpand.getRetnRisk()!=null){
			if (comBackFeeForm.getBackRisk().compareTo(loanapplyExpand.getRetnRisk()) == 1) {
				return BaseRestResult.warn("应退风险补偿金不能大于未退风险补偿金");
			}
		}else{
			if(comBackFeeForm.getBackRisk().compareTo(BigDecimal.ZERO) != 0){
				return BaseRestResult.warn("该单不存在管理费退费需求");
			}
		}
		// 校验银行卡
		String isBankno = BankNoCheckUtil.checkBankNo(comBackFeeForm.getBankAccount());
		if (isBankno.equals(BankNoCheckUtil.IS1619)) {
			return BaseRestResult.warn("银行卡号须16到19之间");
		} else if (isBankno.equals(BankNoCheckUtil.ISNUMBER)) {
			return BaseRestResult.warn("银行卡号必须全为数字");
		} else if (isBankno.equals(BankNoCheckUtil.ISNOT)) {
			return BaseRestResult.warn("银行卡号不符合规范");
		}
		//退款类型
		String payType = "";
		if(comBackFeeForm.getBackDeposite().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_DEP+",";
		}
		if(comBackFeeForm.getBackManger().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_MAN+",";
		}
		
		if(comBackFeeForm.getBackRisk().compareTo(BigDecimal.ZERO) != 0){
			payType =payType + StatusContexts.LOANTYPEO2O_RISK+",";
		}
		if(payType.length()>0){
		payType=payType.substring(0,payType.length()-1);//去除最后一个字符
		}
		comBackFeeForm.setPayType(payType);
		
		O2OComBackFee ComBackFeedb= o2OComBankFeeService.queryEntity(comBackFeeForm.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
		// 新增一条老系统退费数据
		 if(ComBackFeedb==null){
				O2OComBackFee o2OComBackFee = new O2OComBackFee();
				O2oComBackFeeTransFormart.fromToFee(o2OComBackFee, comBackFeeForm);
				OaBackFeeEntity oaBackFeeEntity1 = o2OComBankFeeService.findOaBackFeeById(comBackFeeForm.getLoanapplyNo());
				o2OComBackFee.setBillCode(oaBackFeeEntity1.getBillCode());
				QueryCustomerVO vo = new QueryCustomerVO();
				o2OComBackFee.setAccountName(oaBackFeeEntity1.getUserName());
				o2OComBackFee.setDataSource(StatusContexts.DATA_SOURCE_OLD);
				o2OComBackFee.setLoanerName(oaBackFeeEntity1.getUserName());
				o2OComBackFee.setBillStatus(StatusContexts.WFTYPE_STATUS_NEW);
				o2OComBackFee.setCreatorId(userUtils.getCreateOr());
				o2OComBackFee.setCreatTime(userUtils.getCreateTime());
				o2OComBackFee.setCreatorName(userUtils.getUserName());
				o2OComBankFeeService.save(o2OComBackFee);
				o2OComBankFeeService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_NEW, oaBackFeeEntity1.getLoanapplyno());
		 }else{
			 O2oComBackFeeTransFormart.fromToFee(ComBackFeedb, comBackFeeForm);
			 o2OComBankFeeService.updateById(ComBackFeedb);
		 }
		 if(ComBackFeeForm.TYPE_SAVEANDSTART.equals(comBackFeeForm.getType())){ //如果是保存并启动，调用启动方法
			 //先查出要启动的对象
			 O2OComBackFee startO2OComBackFee =  o2OComBankFeeService.queryEntity(comBackFeeForm.getLoanapplyNo(), StatusContexts.WFTYPE_STATUS_NEW);
			 oaStartUp(startO2OComBackFee.getId());
			 //==
		 }
		 return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/backfee/list"));
	}
	
	@RequestMapping(value = "/backfeestartup")
	public BaseRestResult<String> oaStartUp(String referId) {
		O2OComBackFee o2OComBackFee = o2OComBankFeeService.queryById(referId); 
		O2oLoanapplyEntity apply = null;
		if(o2OComBackFee.getDataSource().equals(StatusContexts.DATA_SOURCE_OLD)){
			OaBackFeeEntity oaBackFeeEntity = o2OComBankFeeService.findOaBackFee(o2OComBackFee.getBillCode());
			apply = OaBackFeeTransO2Oloanapply.transO2oLoanapplyEntity(oaBackFeeEntity);
		}else{
			apply = o2oLoanapplyService.fingByBillCode(o2OComBackFee.getBillCode());
			String ishasHB_Deposit  = o2OComBankFeeService.checkIsHasHB_Deposit(o2OComBackFee.getBillCode()); //判断是否有保证金划拨
			if(!ishasHB_Deposit.equals("0")&&o2OComBackFee.getBackDeposite().compareTo(BigDecimal.ZERO)!=0){
				return BaseRestResult.warn("该单已经存在保证金划拨，如需退保证金，请等待划拨流程走完，如需退其它金额，请将保证金填写为零");
			}
		}
		
		// 存库成功 启动退费流程
		ModelResult<Boolean> modelResult = o2OComBankFeeService.backFee(apply);
		// 流程启动后更新主表
		logger.info("start-up Technological process result params isSuccess:{},ErrCode:{},ErrMsg:{},etailStack:{}", modelResult.isSuccess(), modelResult.getErrCode(), modelResult.getErrMsg(), modelResult.getDetailStack());
		if (modelResult.isSuccess()) {
			o2OComBankFeeService.updateWorkFlowStatus(StatusContexts.WFTYPE_STATUS_RUN, apply.getLoanapplyNo());
			// 流程启动后更新主表
			return BaseRestResult.info("操作成功").andRedirect(UrlHelper.build("/backfee/list"));
		}
		return BaseRestResult.warn(modelResult.getErrMsg());
	}

	/**
	 * @Description:
	 *               <p>
	 *               http://tick.o2ojr.eascs.com/ticket/view/loan-10517
	 *               退保证金与管理费资金部付款节点增加可编辑实际付款日期字段
	 *               </p>
	 * @author CXW
	 * @date 2016年11月4日 上午11:23:12
	 * @version V1.0
	 */
	@RequestMapping(value = "/upLoanTime")
	public BaseRestResult<String> actualLoanTime(ComBackFeeWorkForm comBackFeeWorkForm) {
		if (StringUtil.isEmpty(comBackFeeWorkForm.getActualLoanTime())) {
			return BaseRestResult.warn("请选择实际付款日期");
		} else {
			O2OComBackFee o2OComBackFee = o2OComBankFeeService.queryEntity(comBackFeeWorkForm.getReferId(),
					StatusContexts.WFTYPE_STATUS_RUN);
			o2OComBackFee.setPayDate(DateUtils.formateStandDate(comBackFeeWorkForm.getActualLoanTime()));
			int i = o2OComBankFeeService.updateById(o2OComBackFee);
			if (i > 0) {
				return BaseRestResult.info("保存成功");
			}
			return BaseRestResult.warn("保存失败");
		}
	}
}
